package com.laopan.wxpay.request.refund;

import com.laopan.wxpay.WxConstants;
import com.laopan.wxpay.bean.refund.Refund;
import com.laopan.wxpay.bean.refund.RefundResult;
import com.laopan.wxpay.config.WxPayConfig;
import com.laopan.wxpay.exception.WxPayException;
import com.laopan.wxpay.request.RequestCallback;
import com.laopan.wxpay.request.WxPayRequest;
import com.laopan.wxpay.utils.JsonUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;

/**
 * <p>
 *
 * </p>
 *
 * @author laopan
 * @className DomesticRefund
 * @date 2021/3/8 16:49
 */

public class DomesticRefund extends WxPayRequest<Refund, RefundResult> {
    public DomesticRefund(WxPayConfig wxPayConfig) {
        super(wxPayConfig);
    }

    @Override
    protected Class<RefundResult> getResultClass() {
        return RefundResult.class;
    }

    public RefundResult defaultRefund(Refund refund) throws WxPayException {
        return post(WxConstants.REFUND_PATH, refund, response -> {
            RefundResult result1;
            int code = response.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                try {
                    String resultStr = EntityUtils.toString(entity);
                    result1 = JsonUtils.fromJson(resultStr, RefundResult.class);
                } catch (Exception e) {
                    throw new WxPayException("转出数据出现异常");
                }
            } else {
                throw new WxPayException("微信支付退款失败,微信退款返回码：" + code);
            }
            return result1;
        });
    }

    public RefundResult refund(Refund refund) throws WxPayException {
        return post(WxConstants.REFUND_PATH, refund, null);
    }

    public RefundResult refund(Refund refund, RequestCallback<RefundResult> requestCallback) throws WxPayException {
        return post(WxConstants.REFUND_PATH, refund, requestCallback);
    }
}
